import md5 from 'js-md5'
import router from '@/router'
import {state} from '@/store'
import { forEach,cloneDeep } from 'lodash'
import { useScriptTag } from '@vueuse/core'
import SparkMD5 from "spark-md5";
import {toRaw} from "vue";
//切换皮肤的方法
export function changeSkin(content,type) {
    let head = document.getElementsByTagName("head")[0];
    const getStyle = head.getElementsByTagName('style');
    // 查找style是否存在，存在的话需要删除dom
    if (getStyle.length > 0) {
        for(let i in getStyle){
            try {
                if (getStyle[i].getAttribute('data-type') === type) {
                    getStyle[i].remove();
                }
            }catch (e){

            }
        }
    }
    // 最后加入对应的主题和加载less的js文件
    let styleDom = document.createElement("style");
    styleDom.dataset.type = type;
    styleDom.innerHTML = content;
    head.appendChild(styleDom);
}

export function findIndex(arr,key,findContent){
    return arr.findIndex(item => {
        return item[key] === findContent
    })
}

export function setObjectValue(obj, path, value) {
    const arr = path.split('.')
    const len = arr.length - 1
    arr.reduce((cur, key, index) => {
        if (index === len) {
            cur[key] = value
        }else if(cur[key] === undefined){
            cur[key] = {}
        }
        return cur[key]
    }, obj)
}
export function getObjectValue(obj, path,defaultValue = undefined) {
    const arr = path.split('.')
    let tempObj = obj
    let index = 0
    for (let i=0; i < arr.length; i++) {
        if (!tempObj) break
        const key = arr[i]
        if (key in tempObj) {
            tempObj = tempObj[key]
        } else {
            break
        }
        index++
    }
    return (index === arr.length)? tempObj : defaultValue
}
export function isNumber(value) {
    if (parseFloat(value).toString() == "NaN") {
        return false;
    } else {
        return true;
    }
}
//跳转
export function jump(url) {
    if (/^(https?:|mailto:|tel:)/.test(url)) {
        window.open(url)
    } else {
        if(url.indexOf('/') === 0){
            router.push(url)
        }else{
            router.push('/' + url)
        }
    }
}
export function arrFindNotChildren(arr) {
    for (let key in arr) {
        if (arr[key].children) {
            let item = arrFindNotChildren(arr[key].children)
            if (item) {
                return item
            }
        }
        return arr[key]
    }
    return null
}
export function arrFind(arr, field ,value,level=-1,childrenName = 'children') {
    for (let key in arr) {
        if (arr[key][field] == value) {
            return arr[key]
        }
        if (arr[key][childrenName]) {
            if(level === -1 || level > 1){
                if(level > 1){
                    level--
                }
                let item = arrFind(arr[key][childrenName], field,value,level)
                if (item) {
                    return item
                }
            }
        }
    }
    return null
}

export function findParentList(arr, pid,field='id',pidField='pid',childrenName = 'children') {
    let list = [], find
    do {
        find = arrFind(arr,  field,pid,-1,childrenName)
        if (find) {
            list.unshift(find)
            pid = find[pidField]
        }
    } while (find)
    return list
}
export function getPopupEl(el) {
    if(el.className.indexOf('ant-modal') > -1 || el.className.indexOf('ant-drawer') > -1){
        return el
    }
    if(el.parentElement) {
        return getPopupEl(el.parentElement)
    }
    return null
}
export function offsetLeft(el,filterClass = []) {
    for(let key in filterClass){
        if(el.className.indexOf(filterClass[key]) > -1){
            return 0
        }
    }
    if(el.offsetParent) {
        return offsetLeft(el.offsetParent,filterClass) + el.offsetLeft
    }
    return el.offsetLeft
}
export function offsetTop(el,filterClass = []) {
    for(let key in filterClass){
        if(el.className.indexOf(filterClass[key]) > -1){
            return 0
        }
    }
    if(el.offsetParent) {
        return offsetTop(el.offsetParent,filterClass) + el.offsetTop
    }
    return el.offsetTop
}
export function findParent(arr, pid) {
    let find
    do {
        find = arrFind(arr,  'id',pid)
        if (find) {
            pid = find.pid
            if(pid === 0){
                break
            }
        }
    } while (find)
    return find
}
export function treeMapFilter(datas, field,conditionField) {
    let data = [];
    let keys = [];
    const mapData = datas.filter(item => {
        if (item.children) {
            // @ts-ignore
            data = data.concat(treeMapFilter(item.children, field,conditionField))

        }
        if(item[conditionField]){
            return true
        }
        return false
    });
    data = data.concat(mapData)
    keys = data.map(item=>{
        if(item[field]){
            return item[field]
        }
        return item
    })
    return keys
}
export function loadScript(src){
    return new Promise((resolve, reject) =>{
        useScriptTag(src,el=>{
            resolve(el)
        })
    })
}
//翻译
export function trans(name,replace = {}){
    let content =  getObjectValue(state.locale,name)
    for (let key in replace){
        content = content.replace('{'+key+'}',replace[key])
    }
    return content
}
// 上移
export function ArrUp (arr,index) {
    if (index > 0) {
        const len = arr[index - 1]
        arr[index - 1] = arr[index]
        arr[index] = len
    }

}
// 下移
export function ArrDown (arr,index) {
    if (index < arr.length - 1) {
        const len = arr[index + 1]
        arr[index + 1] = arr[index]
        arr[index] = len
    }
}
export function lastName(path, filename= '') {
    path = path.toString()
    if (filename) {
        return filename
    } else {
        const index = path.lastIndexOf('\/');
        return path.substring(index + 1, path.length)
    }
}
export function fileIcon(path) {
    path = path.toString()
    var index =  path .toString().lastIndexOf('\.')
    var ext = path.substring(index + 1, path.length)
    try {
        return import.meta.env.BASE_URL + 'file_icon/' + ext + '.png'
    } catch (e) {
        return ''
    }
}
//生成随机字母
export function randomCoding(length){
    //创建26个字母数组
    var arr = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
    var idvalue ='';
    for(var i=0;i<length;i++){
        idvalue+=arr[Math.floor(Math.random()*26)];
    }
    return idvalue;
}
export function uniqidMd5() {
    const rand = ('0000' + (Math.random() * Math.pow(36, 4) << 0).toString(36)).slice(-4)
    return md5(rand)
}
export function deleteArr(arr, value) {
    for (let i = arr.length; i > 0; i--) {
        if (arr[i - 1] == value) {
            arr.splice(i - 1, 1)
        }
    }
}
export function empty(value) {
    if(!value && value !== 0){
        return true
    }
    if(Array.isArray(value) && value.length == 0){
        return true
    }
    return false
}
export function treeArray(source, id, parentId, children){
    let cloneData = JSON.parse(JSON.stringify(source))
    return cloneData.filter(father=>{
        let branchArr = cloneData.filter(child => father[id] == child[parentId]);
        branchArr.length>0 ? father[children] = branchArr : ''
        return father[parentId] == 0    // 如果第一层不是parentId=0，请自行修改
    })
}

// 调用时，字段名以字符串的形式传参，如treeData(source, 'id', 'parentId', 'children')
export function file_md5(file) {
    var blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice,
        chunkSize = 2097152,                           // read in chunks of 2MB
        chunks = Math.ceil(file.size / chunkSize),
        currentChunk = 0,
        spark = new SparkMD5(),
        observer = {},
        fileReader = new FileReader();

    fileReader.onload = function (e) {
        spark.appendBinary(e.target.result);                 // append array buffer
        currentChunk += 1;
        if(observer.onProgress){
            observer.onProgress(parseInt(currentChunk / chunks * 100))
        }
        if (currentChunk < chunks) {
            loadNext();
        } else {
            if(observer.onSuccess){
                observer.onSuccess(spark.end())
            }
        }
    };
    fileReader.onerror = function () {
        console.log("something went wrong");
    };
    //监听事件
    function watch(options) {
        //进度
        if(options.progress){
            observer.onProgress = options.progress
        }
        if(options.success){
            observer.onSuccess = options.success
        }
    }
    function loadNext() {
        var start = currentChunk * chunkSize,
            end = start + chunkSize >= file.size ? file.size : start + chunkSize;

        fileReader.readAsBinaryString(blobSlice.call(file, start, end));
    }
    loadNext()
    return {watch}
}
export function fromHex(color){
    var t = {},
        bits = (color.length == 4) ? 4 : 8,//假设是shorthand。 #fff, 那么bits为4位, 每一位代表的个属性, 其他的为8位 每两位代表一个属性 #ffffff00
        mask = (1 << bits) - 1; //表示字节占位符。 向左移4位或8位，var a = (1 << 4 ) - 1 -> 10000 - 1,  a.toString(2); // 1111。或者 8位的 1111 1111
    color = Number("0x" + color.substr(1)); //#ff0000 转变为16进制0xff0000;
    if(isNaN(color)){
        return null; // Color
    }
    ["b", "g", "r"].forEach(function(x){
        var c = color & mask;
        color >>= bits;
        t[x] = bits == 4 ? 17 * c : c; // 0xfff ， 一个f应该代表 255, 应该当[0-255]，按15等份划分，每一等份间隔 17。
    });
    return t;	// Color

}
/**
 * 过滤排除字段
 * @param data
 */
export function exceptField(data,except,parent = []){

    forEach(data,function (value,key){
        let arr = [...parent]
        arr.push(key)
        let str = arr.join('.')
        if(except.indexOf(str) > -1){
            delete data[key]
        }else if(Array.isArray(value)){
            let pid = [...parent]
            pid.push(key)
            forEach(value,function (many) {
                exceptField(many,except,pid)
            })
        }
    })
}
export function compareArrToAttr(arr1,arr2,field){
    let result = []

    forEach(arr1,function (value,index){
        if(arr2[index] && value[field] != arr2[index][field]){
            result.push({
                index:index,
                value:value[field],
                oldValue:arr2[index][field],
            })
        }
    })
    return result
}
//赋值方法
export function setProxyData(data, type,model)
{
    model = toRaw(model)
    for (let field in data.bind) {
        if (type === 1)
        {
            if(field.indexOf('{once}') > -1){
                const f = field.replace('{once}','')
                data.bind[f] = data.bind[field]
                setObjectValue(model,f,data.bind[field])
                delete data.bind[field]
            }else if(!model.hasOwnProperty(field)){
                model[field] = data.bind[field]
            }
        }
        if (model.hasOwnProperty(field) && type === 0) {
            delete model[field]
        }
    }

    for (let slot in data.content) {
        data.content[slot].forEach(item => {
            if (item && typeof (item) == 'object') {
                setProxyData(item, type,model)
            }
        })
    }
}